#!/usr/bin/env python3
"""
数据初始化脚本
用于初始化系统基础数据
"""

import sys
import os
from contextlib import contextmanager
from datetime import datetime, date
import random

# 将项目根目录添加到Python路径中
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))

from sqlalchemy.orm import Session
from app.config.database import get_db, SessionLocal
from app.models.teacher import Teacher
from app.models.classroom import Classroom
from app.models.course import Course
from app.models.academic_year import AcademicYear
from app.models.class_model import Class
from app.models.class_student import ClassStudent
from app.models.student import Student
from app.models.role import Role
from app.models.permission import Permission
from app.models.role_permission import RolePermission
from app.utils.logger import logger

def init_base_data():
    """初始化基础数据"""
    db_gen = get_db()
    db: Session = next(db_gen)

    try:
        # 检查是否已存在数据
        # 如果需要重新初始化，可以取消下面的注释
        # if db.query(Course).count() > 0:
        #     print("基础数据已存在，跳过初始化")
        #     return True

        # 清理已存在的数据
        db.query(ClassStudent).delete()
        db.query(Class).delete()
        db.query(AcademicYear).delete()
        db.query(Classroom).delete()
        db.query(Course).delete()
        db.commit()

        print("开始初始化基础数据...")

        # 1. 初始化课程数据
        print("初始化课程数据...")
        courses_data = [
            {"course_code": "CHINESE", "course_name": "语文", "course_type": 1, "grade_range": "1-5", "course_hours": 160},
            {"course_code": "MATH", "course_name": "数学", "course_type": 1, "grade_range": "1-5", "course_hours": 120},
            {"course_code": "PE", "course_name": "体育", "course_type": 2, "grade_range": "1-5", "course_hours": 80},
            {"course_code": "SCIENCE", "course_name": "科学", "course_type": 1, "grade_range": "1-5", "course_hours": 60},
            {"course_code": "PD_LIFE", "course_name": "品德与生活", "course_type": 1, "grade_range": "1-2", "course_hours": 40},
            {"course_code": "PD_SOCIAL", "course_name": "品德与社会", "course_type": 1, "grade_range": "3-5", "course_hours": 40},
            {"course_code": "FOREIGN_LANG", "course_name": "外语", "course_type": 1, "grade_range": "3-5", "course_hours": 80},
            {"course_code": "MUSIC", "course_name": "音乐", "course_type": 2, "grade_range": "1-5", "course_hours": 40},
            {"course_code": "FINE_ART", "course_name": "美术", "course_type": 2, "grade_range": "1-5", "course_hours": 40},
            {"course_code": "ART", "course_name": "艺术", "course_type": 2, "grade_range": "1-2", "course_hours": 40},
            {"course_code": "COMPREHENSIVE", "course_name": "综合实践活动", "course_type": 3, "grade_range": "3-5", "course_hours": 40},
            {"course_code": "IT", "course_name": "信息技术", "course_type": 1, "grade_range": "3-5", "course_hours": 40},
        ]

        for course_data in courses_data:
            course = Course(**course_data)
            db.add(course)

        # 2. 初始化教室数据（完整80间教室）
        print("初始化教室数据...")
        classrooms_data = []

        # 1楼教室（20间）
        for i in range(1, 21):
            room_no = i
            classrooms_data.append({
                "classroom_code": f"101{room_no:02d}",
                "classroom_name": f"1{room_no:02d}教室",
                "building_no": 1,
                "floor_no": 1,
                "room_no": room_no,
                "capacity": 60,
                "room_type": 1
            })

        # 2楼教室（20间）
        for i in range(1, 21):
            room_no = i
            classrooms_data.append({
                "classroom_code": f"102{room_no:02d}",
                "classroom_name": f"2{room_no:02d}教室",
                "building_no": 1,
                "floor_no": 2,
                "room_no": room_no,
                "capacity": 60,
                "room_type": 1
            })

        # 3楼教室（20间）
        for i in range(1, 21):
            room_no = i
            classrooms_data.append({
                "classroom_code": f"103{room_no:02d}",
                "classroom_name": f"3{room_no:02d}教室",
                "building_no": 1,
                "floor_no": 3,
                "room_no": room_no,
                "capacity": 60,
                "room_type": 1
            })

        # 4楼教室（20间）
        for i in range(1, 21):
            room_no = i
            classrooms_data.append({
                "classroom_code": f"104{room_no:02d}",
                "classroom_name": f"4{room_no:02d}教室",
                "building_no": 1,
                "floor_no": 4,
                "room_no": room_no,
                "capacity": 60,
                "room_type": 1
            })

        for classroom_data in classrooms_data:
            classroom = Classroom(**classroom_data)
            db.add(classroom)

        # 3. 初始化学年学期数据
        print("初始化学年学期数据...")
        academic_years_data = [
            {
                "year_code": "2025-2026",
                "year_name": "2025-2026学年",
                "start_date": date(2025, 9, 1),
                "end_date": date(2026, 7, 15),
                "semester": 1,
                "is_current": True
            },
            {
                "year_code": "2025-2026",
                "year_name": "2025-2026学年",
                "start_date": date(2026, 2, 15),
                "end_date": date(2026, 7, 15),
                "semester": 2,
                "is_current": False
            }
        ]

        for academic_year_data in academic_years_data:
            academic_year = AcademicYear(**academic_year_data)
            db.add(academic_year)

        db.commit()

        db.commit()

        # 4. 初始化权限数据
        print("初始化权限数据...")
        permissions_data = [
            # 系统管理权限
            {"perm_code": "SYS_USER_MANAGE", "perm_name": "用户管理", "perm_type": 3},
            {"perm_code": "SYS_ROLE_MANAGE", "perm_name": "角色管理", "perm_type": 3},
            {"perm_code": "SYS_PERMISSION_MANAGE", "perm_name": "权限管理", "perm_type": 3},

            # 用户管理权限
            {"perm_code": "USER_STUDENT_MANAGE", "perm_name": "学生管理", "perm_type": 3},
            {"perm_code": "USER_TEACHER_MANAGE", "perm_name": "教师管理", "perm_type": 3},

            # 教务管理权限
            {"perm_code": "EDU_CLASSROOM_MANAGE", "perm_name": "教室管理", "perm_type": 3},
            {"perm_code": "EDU_COURSE_MANAGE", "perm_name": "课程管理", "perm_type": 3},
            {"perm_code": "EDU_ACADEMIC_YEAR_MANAGE", "perm_name": "学年管理", "perm_type": 3},
            {"perm_code": "EDU_CLASS_MANAGE", "perm_name": "班级管理", "perm_type": 3},
            {"perm_code": "EDU_CLASS_STUDENT_MANAGE", "perm_name": "班级学生管理", "perm_type": 3},
        ]

        permission_ids = {}
        for perm_data in permissions_data:
            permission = Permission(**perm_data)
            db.add(permission)
            db.flush()
            permission_ids[perm_data["perm_code"]] = permission.id

        # 5. 初始化角色权限关联
        print("初始化角色权限关联...")
        # 系统管理员拥有所有权限
        admin_role = db.query(Role).filter(Role.role_code == "ADMIN").first()
        if admin_role:
            for perm_id in permission_ids.values():
                role_perm = RolePermission(role_id=admin_role.id, permission_id=perm_id)
                db.add(role_perm)

        # 教务管理员拥有教务管理权限
        edu_admin_role = db.query(Role).filter(Role.role_code == "EDU_ADMIN").first()
        if edu_admin_role:
            edu_permissions = [
                "USER_STUDENT_MANAGE", "USER_TEACHER_MANAGE",
                "EDU_CLASSROOM_MANAGE", "EDU_COURSE_MANAGE",
                "EDU_ACADEMIC_YEAR_MANAGE", "EDU_CLASS_MANAGE", "EDU_CLASS_STUDENT_MANAGE"
            ]
            for perm_code in edu_permissions:
                if perm_code in permission_ids:
                    role_perm = RolePermission(role_id=edu_admin_role.id, permission_id=permission_ids[perm_code])
                    db.add(role_perm)

        # 6. 初始化班级数据（完整50个班级）
        print("初始化班级数据...")
        classes_data = []

        # 获取学年ID
        academic_year = db.query(AcademicYear).filter(AcademicYear.is_current == True).first()
        if not academic_year:
            print("未找到当前学年数据")
            return False

        academic_year_id = academic_year.id

        # 一年级10个班
        for i in range(1, 11):
            classes_data.append({
                "class_code": f"202501{i:02d}",
                "class_name": f"一年级{i}班",
                "academic_year_id": academic_year_id,
                "grade": 1,
                "class_no": i
            })

        # 二年级10个班
        for i in range(1, 11):
            classes_data.append({
                "class_code": f"202502{i:02d}",
                "class_name": f"二年级{i}班",
                "academic_year_id": academic_year_id,
                "grade": 2,
                "class_no": i
            })

        # 三年级10个班
        for i in range(1, 11):
            classes_data.append({
                "class_code": f"202503{i:02d}",
                "class_name": f"三年级{i}班",
                "academic_year_id": academic_year_id,
                "grade": 3,
                "class_no": i
            })

        # 四年级10个班
        for i in range(1, 11):
            classes_data.append({
                "class_code": f"202504{i:02d}",
                "class_name": f"四年级{i}班",
                "academic_year_id": academic_year_id,
                "grade": 4,
                "class_no": i
            })

        # 五年级10个班
        for i in range(1, 11):
            classes_data.append({
                "class_code": f"202505{i:02d}",
                "class_name": f"五年级{i}班",
                "academic_year_id": academic_year_id,
                "grade": 5,
                "class_no": i
            })

        for class_data in classes_data:
            class_item = Class(**class_data)
            db.add(class_item)

        db.commit()
        print("基础数据初始化完成！")
        return True

    except Exception as e:
        db.rollback()
        print(f"数据初始化失败: {e}")
        return False
    finally:
        db.close()

def init_teacher_student_data():
    """初始化教师和学生数据"""
    db_gen = get_db()
    db: Session = next(db_gen)

    try:
        print("开始初始化教师和学生数据...")

        # 获取班级数据
        classes = db.query(Class).all()
        if not classes:
            print("未找到班级数据，请先初始化基础数据")
            return False

        # 1. 初始化教师数据（约450人）
        print("初始化教师数据...")
        # 主科教师（语文、数学、英语）占比较高
        main_subjects = ["语文", "数学", "英语"]
        other_subjects = ["科学", "体育", "音乐", "美术", "信息技术", "品德"]

        teacher_job_titles = [
            "初级教师", "中级教师", "高级教师", "特级教师", "教研组长", "副校长"
        ]

        # 常见中文姓名（姓氏）
        last_names = [
            "王", "李", "张", "刘", "陈", "杨", "赵", "黄", "周", "吴",
            "徐", "孙", "胡", "朱", "高", "林", "何", "郭", "马", "罗",
            "梁", "宋", "郑", "谢", "韩", "唐", "冯", "于", "董", "萧"
        ]

        # 常见中文姓名（名字）
        first_names_male = [
            "伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军",
            "洋", "勇", "艳", "杰", "娟", "涛", "明", "超", "秀兰", "霞",
            "平", "刚", "桂英", "辉", "鹏", "华", "丽", "亮", "成", "琴"
        ]

        first_names_female = [
            "伟", "芳", "娜", "秀英", "敏", "静", "丽", "强", "磊", "军",
            "洋", "勇", "艳", "杰", "娟", "涛", "明", "超", "秀兰", "霞",
            "平", "刚", "桂英", "辉", "鹏", "华", "丽", "亮", "成", "琴"
        ]

        # 生成教师数据（450人）
        for i in range(1, 451):
            # 随机生成姓名
            last_name = random.choice(last_names)
            gender = random.choice([1, 2])  # 1-男 2-女
            if gender == 1:
                first_name = random.choice(first_names_male)
            else:
                first_name = random.choice(first_names_female)

            teacher_name = last_name + first_name
            teacher_no = f"T2025{str(i).zfill(4)}"

            # 调整科目分配，主科教师占70%
            if random.random() < 0.7:  # 70%概率是主科教师
                subject = random.choice(main_subjects)
            else:  # 30%概率是非主科教师
                subject = random.choice(other_subjects)

            # 随机选择职称
            job_title = random.choice(teacher_job_titles)

            # 随机生成出生日期（25-55岁）
            birth_year = random.randint(1970, 2000)
            birth_month = random.randint(1, 12)
            birth_day = random.randint(1, 28)  # 简化处理，避免闰年问题
            birth_date = date(birth_year, birth_month, birth_day)

            teacher_data = {
                "user_id": 0,  # 无用户关联
                "teacher_no": teacher_no,
                "teacher_name": teacher_name,
                "gender": gender,
                "birth_date": birth_date,
                "phone": f"138{random.randint(10000000, 99999999)}",
                "email": f"{teacher_name}@myth.edu.cn",
                "subject_code": subject,
                "job_title": job_title,
                "status": 1
            }

            teacher = Teacher(**teacher_data)
            db.add(teacher)

            # 每100条提交一次
            if i % 100 == 0:
                db.commit()
                print(f"已初始化 {i} 名教师...")

        db.commit()
        print("教师数据初始化完成！")

        # 2. 初始化学生数据（约2200-2500人）
        print("初始化学生数据...")

        # 生成学生数据（每班40-50人）
        student_count = 0
        for class_item in classes:
            # 每个班级40-50名学生
            students_per_class = random.randint(40, 50)
            for i in range(1, students_per_class + 1):
                student_count += 1

                # 随机生成姓名
                last_name = random.choice(last_names)
                gender = random.choice([1, 2])  # 1-男 2-女
                if gender == 1:
                    first_name = random.choice(first_names_male)
                else:
                    first_name = random.choice(first_names_female)

                student_name = last_name + first_name
                student_no = f"S2025{str(student_count).zfill(5)}"

                # 随机生成出生日期（根据年级）
                birth_year = 2025 - class_item.grade - 6  # 例如一年级学生约6岁入学
                birth_month = random.randint(1, 12)
                birth_day = random.randint(1, 28)  # 简化处理，避免闰年问题
                birth_date = date(birth_year, birth_month, birth_day)

                student_data = {
                    "user_id": 0,  # 无用户关联
                    "student_no": student_no,
                    "student_name": student_name,
                    "gender": gender,
                    "birth_date": birth_date,
                    "phone": f"139{random.randint(10000000, 99999999)}",
                    "address": f"北京市朝阳区{random.randint(1, 200)}号",
                    "parent_name": last_name + random.choice(first_names_male),
                    "parent_phone": f"136{random.randint(10000000, 99999999)}",
                    "status": 1
                }

                student = Student(**student_data)
                db.add(student)

                # 创建班级学生关联
                class_student_data = {
                    "class_id": class_item.id,
                    "student_id": student_count,  # 使用自增ID
                    "join_date": date(2025, 9, 1),
                    "status": 1
                }

                class_student = ClassStudent(**class_student_data)
                db.add(class_student)

                # 每500条提交一次
                if student_count % 500 == 0:
                    db.commit()
                    print(f"已初始化 {student_count} 名学生...")

        db.commit()
        print(f"学生数据初始化完成！总共初始化了 {student_count} 名学生")
        print("教师和学生数据初始化完成！")
        return True

    except Exception as e:
        db.rollback()
        print(f"教师和学生数据初始化失败: {e}")
        return False
    finally:
        db.close()

def update_class_student_data():
    """
    查出所有的班级信息 classes = db.query(Class).all()，和所有老师Teacher
    统计ClassStudent 班级有多少学生
    更新classes student_count，选择一个主课老师担任班主任
    """
    try:
      db_gen = get_db()
      db: Session = next(db_gen)
      classes = db.query(Class).all()
      teachers = db.query(Teacher).all()
      main_subjects = ["语文", "数学", "英语"]
      teachers = [teacher for teacher in teachers if teacher.subject_code in main_subjects]
      for class_item in classes:
          class_student_count = db.query(ClassStudent).filter(ClassStudent.class_id == class_item.id).count()
          class_item.student_count = class_student_count
          class_item.head_teacher_id = random.choice(teachers).id
          db.add(class_item)
      # 提交事务
      db.commit()

    except Exception as e:
        db.rollback()
        print(f"更新班级学生信息失败: {e}")
        return False
    finally:
        db.close()
# source .venv/bin/activate && python scripts/init_data.py
def main():
    """主函数"""
    # 保留但不执行init_base_data函数
    init_base_data()

    # 执行新的教师和学生数据初始化函数
    init_teacher_student_data()
    # 执行班级学生数据更新函数
    update_class_student_data()

if __name__ == "__main__":
    main()